package com.irheima.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/cookie/*")
public class CookieServlet extends BaseServlet {

    public void test(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//      获取提交的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//          判断能否登录
        if("why".equals(username)&&"123456".equals(password)){
//          获取Cookie对象
            Cookie cookieName = new Cookie("username", username);
            Cookie cookiepwd = new Cookie("pwd", password);
            //获取页面复选框状态
            String ck = req.getParameter("ck");
            if(ck!=null){ //选中保存
                //          设置存活时间
                cookieName.setMaxAge(1*24*60*60);
                cookiepwd.setMaxAge(1*24*60*60);
            }else {        //不保存
                cookieName.setMaxAge(0);
                cookiepwd.setMaxAge(0);
            }
//           设置访问路径
            cookieName.setPath("/");
            cookiepwd.setPath("/");
//          传给页面
            resp.addCookie(cookieName);
            resp.addCookie(cookiepwd);

//          重定向到成功登录
            resp.sendRedirect(req.getContextPath()+"/page/success.jsp");
        }else {
            resp.sendRedirect(req.getContextPath()+"/page/login.jsp");

        }


    }
}
